package com.substation.ui.activity;

import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bean.LoginInfo;
import com.greenentity.Area;
import com.greenentity.Defect;
import com.greenentity.Inspect;
import com.greenentity.Photo;
import com.greenentity.Ready;
import com.greenentity.SafetyCard;
import com.greenentity.SafetyTool;
import com.greenentity.Substation;
import com.greenentity.Task;
import com.greenentity.Unit;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;
import com.net.SubstationNet;
import com.substation.R;
import com.substation.greendao.PhotoDao;
import com.substation.greendao.SubstationDao;
import com.substation.greendao.TaskDao;
import com.substation.utils.GreenDaoManager;
import com.substation.utils.SPUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 任务
 */
public class TaskActivity extends BaseListActivity {

    SuperAdapter<Task> adapter;
    List<Task> datas = new ArrayList<>();
    int flag = 0;//0-本地.1-服务器
    Task downTask = null;//点击下载的task
    @BindView(R.id.choiseTxt)
    TextView choiseTxt;


    @Override
    protected int getMyListLayoutId() {
        return R.layout.activity_task;
    }

    @Override
    protected void initView() {
        super.initView();
        refresh.setRefreshing(false);
        refresh.setEnabled(false);
        choiseTxt.setVisibility(View.VISIBLE);
        choiseTxt.setText("本地");
        adapter.setData(datas);
        adapter.setEmptyDataView(R.layout.view_empty);
    }

    @Override
    protected void initData() {
        super.initData();
        getLocal();
    }

    @Override
    public SuperAdapter getAdapter() {
        return adapter = new SuperAdapter<Task>(R.layout.content_task) {
            @Override
            public void bindView(ViewHolder viewHolder, final Task s, int i) {
                View layout = viewHolder.getView(R.id.layout);
                Button button = viewHolder.getView(R.id.downLoad);
                if (flag == 0) {
                    button.setVisibility(View.GONE);
                    layout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            SPUtils.put(context, "task", JSON.toJSONString(s));
                            if (s.getSafety() == 0)
                                startActivity(new Intent(context, ReadyActivity.class));
                            else
                                startActivity(new Intent(context, PatrolActivity.class));
                        }
                    });
                } else {
                    button.setVisibility(View.VISIBLE);
                    layout.setClickable(false);
                }
                List<Substation> substations = GreenDaoManager.getInstance().getmDaoSession().getSubstationDao().queryBuilder().where(SubstationDao.Properties.Guid.eq(s.getSubsGuid())).list();
                ((TextView) viewHolder.getView(R.id.substation)).setText(substations.size() > 0 ? substations.get(0).getNames() : "未知变电站");
                ((TextView) viewHolder.getView(R.id.classfy)).setText(s.getTourTypevalue());
                ((TextView) viewHolder.getView(R.id.planTime)).setText(s.getPlanTime());
                ((TextView) viewHolder.getView(R.id.person)).setText(s.getDealUserIdvalue());
                ((TextView) viewHolder.getView(R.id.person2)).setText(s.getSupervisorUserIdvalue());
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        downTask = s;
                        SubstationNet.downTourSubsWorkByGuid(context, s.getWorkGuid(), TaskActivity.this);
                    }
                });
            }
        };
    }

    void getLocal() {
        datas.clear();
        datas.addAll(GreenDaoManager.getInstance().getmDaoSession().getTaskDao().queryBuilder().where(TaskDao.Properties.CurrentWfNo.eq("20")
                , TaskDao.Properties.DealUserId.eq(LoginInfo.getInfo(context).getAccountProfileDetails().getObjectId())).list());
        adapter.notifyDataSetChanged();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_see, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.local:
                flag = 0;
                getLocal();
                choiseTxt.setText("本地");
                return true;
            case R.id.service:
                choiseTxt.setText("服务器");
                flag = 1;
                datas.clear();
                SubstationNet.getTourSubsWork(context, this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void success(int i, String obj) {
        switch (i) {
            case 1:
                JSONObject j = JSON.parseObject(obj);
                String data = j.getString("data");
                datas.clear();
                List<Task> serviceTask = JSON.parseArray(data, Task.class);
                for (Task t : serviceTask) {
                    if (GreenDaoManager.getInstance().getmDaoSession().getTaskDao().queryBuilder().where(TaskDao.Properties.WorkGuid.eq(t.getWorkGuid())).count() == 0) {
                        datas.add(t);
                    }
                }
                adapter.notifyDataSetChanged();
                break;
            case 2:
                JSONObject jsonObject = JSON.parseObject(obj);
                String toursubsworkList = jsonObject.getString("toursubsworkList");//任务
                String toursubsworkcardList = jsonObject.getString("toursubsworkcardList");//区域
                String toursubsworkcardunitList = jsonObject.getString("toursubsworkcardunitList");//单元
                String toursubsworkcarditemList = jsonObject.getString("toursubsworkcarditemList");//检查项
                String tourworkdefectList = jsonObject.getString("tourworkdefectList");//历史隐患
                String toursubsworkattentionList = jsonObject.getString("toursubsworkattentionList");//作业前准备
                String tourworktoolList = jsonObject.getString("tourworktoolList");//安全工器具
                String toursubsworksupervisorList = jsonObject.getString("toursubsworksupervisorList");//安全监督卡
                String tourdefectphotoList = jsonObject.getString("tourdefectphotoList");//缺陷图片
                List<Task> tasks = JSON.parseArray(toursubsworkList, Task.class);
                GreenDaoManager.getInstance().getmDaoSession().getTaskDao().insertOrReplaceInTx(tasks);
                List<Area> areas = JSON.parseArray(toursubsworkcardList, Area.class);
                GreenDaoManager.getInstance().getmDaoSession().getAreaDao().insertOrReplaceInTx(areas);
                List<Unit> units = JSON.parseArray(toursubsworkcardunitList, Unit.class);
                GreenDaoManager.getInstance().getmDaoSession().getUnitDao().insertOrReplaceInTx(units);
                List<Inspect> inspects = JSON.parseArray(toursubsworkcarditemList, Inspect.class);
                GreenDaoManager.getInstance().getmDaoSession().getInspectDao().insertOrReplaceInTx(inspects);
                List<Defect> defects = JSON.parseArray(tourworkdefectList, Defect.class);
                GreenDaoManager.getInstance().getmDaoSession().getDefectDao().insertOrReplaceInTx(defects);
                List<Ready> readies = JSON.parseArray(toursubsworkattentionList, Ready.class);
                GreenDaoManager.getInstance().getmDaoSession().getReadyDao().insertOrReplaceInTx(readies);
                List<SafetyTool> safetyTools = JSON.parseArray(tourworktoolList, SafetyTool.class);
                GreenDaoManager.getInstance().getmDaoSession().getSafetyToolDao().insertOrReplaceInTx(safetyTools);
                List<SafetyCard> safetyCards = JSON.parseArray(toursubsworksupervisorList, SafetyCard.class);
                GreenDaoManager.getInstance().getmDaoSession().getSafetyCardDao().insertOrReplaceInTx(safetyCards);
                List<Photo> photos = JSON.parseArray(tourdefectphotoList, Photo.class);
                String guid = "";//记录上次删除的GUID
                for (Photo p : photos) {//删除本地的图片信息，使用服务器上的图片
                    if (p.getDefectGuid() != null && !guid.equals(p.getDefectGuid())) {
                        guid = p.getDefectGuid();
                        GreenDaoManager.getInstance().getmDaoSession().getPhotoDao().queryBuilder()
                                .where(PhotoDao.Properties.DefectGuid.eq(guid)).buildDelete()
                                .executeDeleteWithoutDetachingEntities();
                    }
                }
                GreenDaoManager.getInstance().getmDaoSession().getPhotoDao().insertOrReplaceInTx(photos);
                datas.remove(downTask);
                adapter.notifyDataSetChanged();
                break;
        }
    }
}
